package com.bdqn.systems.auth;


import com.bdqn.response.Result;
import com.bdqn.response.ResultCode;
import com.bdqn.systems.utils.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.*;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author : CP
 * @version: 1.0
 * @program : spring-security-test
 * @description : 登录成功处理
 * @date : 2020-12-18 09:22
 **/
@Component
public class MyAuthenticationSuccessHandler extends JSONAuthentication implements AuthenticationSuccessHandler {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    /**
     * 身份认证成功
     * @param request
     * @param response
     * @param authentication
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        Object principal = authentication.getPrincipal();
        //用户权限
        UserDetails userDetails = null;
        if(principal instanceof UserDetails){
            userDetails = (UserDetails)principal;
        }

        Result result = Result.ok().data("token",jwtTokenUtil.generateToken(userDetails));
        this.WriteJSON(request,response,result);
    }
}
